<template>
  <BasicModal
    v-bind="$attrs"
    @register="registerModal"
    :title="modalTitle"
    cancelText="关闭"
    @cancel="onButtonCancelClick"
    :showOkBtn="false"
    width="800px"
  >
    <BasicTable
      @register="registerMembersTable"
      :can-resize="true"
      :bordered="true"
      :striped="true"
      :loading="false"
      :data-source="ScheduleMembersData.members"
    >
      <!-- 是否是值班长 -->
      <template #chiefFlag="{ record }">
        <template v-if="record.chief === true">
          <Tag :color="'cadetBlue'">是</Tag>
        </template>
        <template v-if="record.chief === false">
          <Tag :color="'DarkGray'">否</Tag>
        </template>
      </template>

      <template #toolbar>
        <a-button type="primary" @click="onShiftMemberList"> 新增 </a-button>
      </template>

      <template #action="{ record }">
        <TableAction
          :actions="[
            {
              icon: 'clarity:note-edit-line',
              label: '编辑',
              onClick: onEditScheduleMember.bind(null, record),
            },
            {
              icon: 'ant-design:delete-outlined',
              label: '删除',
              color: 'error',
              popConfirm: {
                title: '是否确认删除',
                confirm: deleteDutyScheduleMember.bind(null, record),
              },
            },
          ]"
        />
      </template>
    </BasicTable>
    <setDutyScheduleMembers @register="registerMemberList" @success="successReload" />
    <editDutyScheduleMember @register="registerDutyScheduleMemberForm" @success="successReload" />
  </BasicModal>
</template>
<script lang="ts">
  import { defineComponent, ref, reactive, unref, inject, provide } from 'vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { Tag } from 'ant-design-vue';

  import { getShiftMembers, deleteShiftMember } from '/@/api/duty/dutySchedule';
  import { membersTableColumns } from './dutyschedule.data';

  //引入子组件
  import setDutyScheduleMembers from './SetDutyScheduleMembers.vue';
  import editDutyScheduleMember from './EditDutyScheduleMember.vue';

  import { useMessage } from '/@/hooks/web/useMessage';
  import { OperationTypeEnum } from '/@/enums/appEnum';
  import { BasicTable, useTable, TableAction } from '/@/components/Table';

  //使用modal弹出窗口
  import { useModal } from '/@/components/Modal';

  const { createMessage } = useMessage();

  const [registerMemberList, { openModal: openMemberList }] = useModal();
  const [registerDutyScheduleMemberForm, { openModal: openDutyScheduleMemberForm }] = useModal();

  export default defineComponent({
    name: 'DutyScheduleMembersManager',
    components: {
      BasicModal,
      BasicTable,
      TableAction,
      Tag,
      setDutyScheduleMembers,
      editDutyScheduleMember,
    },
    emits: ['success', 'register'],
    setup(_, { emit }) {
      //定义模块的名称，提供给子孙组件获取使用
      const MembersModuleName = ref('班次人员管理');
      provide('MembersModuleName', MembersModuleName);

      //弹出窗口界面是关联部门设置
      const op = ref(OperationTypeEnum.UN_KNOWN);
      //标题--根据传入的模块名称+操作类型组合得到
      const modalTitle = ref('标题');
      const moduleName = inject<string>('moduleName');
      const tableTitle = ref('班次人员管理');

      //排班id
      const dataId = ref('');

      //处理过后的table数据
      const ScheduleMembersData = reactive({
        members: [],
      });

      const [registerMembersTable] = useTable({
        title: tableTitle,
        // api: getTeamMembers,
        // searchInfo: { id: dataId.value }, //请求参数
        columns: membersTableColumns, //表头数据
        showTableSetting: true, //是否显示表格设置
        bordered: true,
        showIndexColumn: true,
        actionColumn: {
          width: 100,
          title: '操作',
          dataIndex: 'action',
          slots: { customRender: 'action' },
          fixed: 'right', //表格操作列是否固定，不设置时默认固定在右侧
        },
        pagination: false, //关闭分页
      });

      /**
       * 接收父组件传递的数据并处理
       */
      const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
        //接收父组件传递的数据
        console.log(data);
        //判断是否传入op属性
        if (data?.op) {
          op.value = data.op;
        }

        //接收排班ID
        if (data?.dataId) {
          dataId.value = data.dataId;
        }

        if (moduleName) {
          modalTitle.value = unref(moduleName);
        }
        if (op.value != OperationTypeEnum.UN_KNOWN && op.value != OperationTypeEnum.CUSTOME) {
          modalTitle.value += '--' + op.value;
        }

        setModalProps({ confirmLoading: false });

        getDutyScheduleMembers();
      });

      /**
       * 获取指定班次的值班成员列表
       */
      async function getDutyScheduleMembers() {
        //更新数据前先清空原来的数据，否则页面不刷新显示最新数据
        if (ScheduleMembersData.members.length > 0) {
          ScheduleMembersData.members = [];
        }
        //调用后端接口获取数据
        getShiftMembers(dataId.value)
          .then((res) => {
            console.log('res', res);
            if (res != null) {
              //处理返回数据
              res.forEach((scheduleMember) => {
                let result = {
                  id: scheduleMember.id,
                  memberid: scheduleMember.memberid,
                  memberName: scheduleMember.member.name,
                  odr: scheduleMember.odr,
                  chief: scheduleMember.chief,
                };
                ScheduleMembersData.members.push(result);
              });
              console.log('ScheduleMembersData', ScheduleMembersData);
            }
          })
          .catch((ex) => {
            console.log('catch ', ex);
            createMessage.error(ex.msg);
          });
      }

      /**
       * 打开新增班次人员窗口
       */
      function onShiftMemberList() {
        openMemberList(true, { op: '新增班次人员', dataId: dataId.value });
      }

      /**
       * 打开编辑班次人员窗口
       */
      function onEditScheduleMember(record: Recordable) {
        openDutyScheduleMemberForm(true, { op: '编辑班次人员', member: record });
      }

      /**
       * 删除班次人员
       */
      function deleteDutyScheduleMember(record: Recordable) {
        deleteShiftMember({ id: record.id, memberid: record.memberid })
          .then((res) => {
            console.log('res', res);
            //res判断结果：同时==undefined和null
            if (res == undefined && (res == null || Object.keys(res).length == 0)) {
              createMessage.success('删除成功。', 2);
              successReload();
            }
          })
          .catch((ex) => {
            console.log('catch ', ex);
            createMessage.error(ex.msg);
          });
      }

      /**
       * 点击确认按钮
       */
      async function onButtonCancelClick() {
        closeModal();
        emit('success');
      }

      /**
       * 确认操作之后刷新页面
       */
      function successReload() {
        getDutyScheduleMembers();
      }

      return {
        op,
        moduleName,
        modalTitle,
        MembersModuleName,
        registerModal,
        registerMembersTable,

        registerMemberList,
        registerDutyScheduleMemberForm,

        successReload,
        onShiftMemberList,
        onEditScheduleMember,
        getDutyScheduleMembers,
        deleteDutyScheduleMember,

        ScheduleMembersData,
        onButtonCancelClick,
      };
    },
  });
</script>
